package com.liyuan.entity;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;

import java.io.IOException;

/**
 * 记录读取器，用于遍历数组数据。
 */
public class ArrayRecordReader extends RecordReader<LongWritable, Text> {
    private long pos = 0;
    private long length;
    private String[] dataArray;
    private LongWritable key = new LongWritable();
    private Text value = new Text();

    /**
     * 初始化记录读取器。
     */
    @Override
    public void initialize(InputSplit split, TaskAttemptContext context)
            throws IOException, InterruptedException {
        ArraySplit arraySplit = (ArraySplit) split;
        this.dataArray = arraySplit.getLocations();
        this.length = arraySplit.getLength();
    }

    /**
     * 获取下一个键值对。
     *
     * @return 如果存在下一个键值对，则返回true；否则返回false。
     * @throws IOException
     * @throws InterruptedException
     */
    @Override
    public boolean nextKeyValue() throws IOException, InterruptedException {
        if (pos >= length) {
            return false;
        }
        key.set(pos++);
        // System.out.println(dataArray[0]);
        value.set(dataArray[(int) pos - 1]);
        return true;
    }

    /**
     * 获取当前键。
     */
    @Override
    public LongWritable getCurrentKey() throws IOException, InterruptedException {
        return key;
    }

    /**
     * 获取当前值。
     */
    @Override
    public Text getCurrentValue() throws IOException, InterruptedException {
        return value;
    }

    /**
     * 获取读取进度。
     *
     * @return 读取进度，范围在0到1之间。
     * @throws IOException
     * @throws InterruptedException
     */
    @Override
    public float getProgress() throws IOException, InterruptedException {
        return (pos == 0) ? 0.0f : Math.min(1.0f, pos / length);
    }

    /**
     * 关闭读取器。
     */
    @Override
    public void close() throws IOException {
        // 可能的清理工作
    }
}